<template>
  <div>
    <!-- 按钮 -->
    <el-button style="margin: 10px 0" icon="el-icon-plus" type="primary" @click="showDialogFn">添加品牌</el-button>

    <!-- 表格组件 -->
    <!-- data：表格的数据来源。border：表格添加边框。 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column type="index" label="序号" align="center" width="150" />
      <el-table-column prop="tmName" label="品牌名称" width="300" />
      <el-table-column prop="logoUrl" label="品牌logo" width="500">
        <template v-slot="{row}">
          <img class="img" :src="row.logoUrl" alt="">
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template v-slot="{row}">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showDialogFn(row)">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeTradeItemFn(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <!-- @size-change="handleSizeChange" -->
    <!-- @current-change="handleCurrentChange" -->
    <!-- current-page：当前第几页
   total：数据总条数
   page-size：每页展示的条数
   page-sizes：设置每页可展示的条数
   layout：实现分页器的布局-->
    <el-pagination
      style="margin-top: 20px; text-align: center;"
      :current-page="page.page"
      :page-sizes="[5, 10, 20, 40]"
      :page-count="5"
      :page-size="page.limit"
      layout="prev, pager, next, jumper, -> , total, sizes"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <el-dialog :title="form.id ? '修改品牌' : '新增品牌'" :visible.sync="dialogFormVisible" @close="closeDialogFn">
      <el-form ref="form" :rules="rules" :model="form">
        <el-form-item prop="tmName" label="品牌名称" label-width="100px">
          <el-input v-model="form.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="logoUrl" label="品牌LOGO" label-width="100px">
          <!-- action:图片上传的地址
        on-success:检测到图片上传成功
        before-upload:上传图片之前执行 -->
          <el-upload
            class="avatar-uploader"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialogFn">取 消</el-button>
        <el-button type="primary" @click="configDialogFn">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    const validateTmName = (rule, value, callback) => {
      if (value.length < 2 || value.length > 10) {
        callback(new Error('品牌名称要2-10位'))
      } else {
        callback()
      }
    }
    return {
      tableData: [], // el-table的数据数组
      page: {
        page: 1,
        limit: 5
      },
      total: 0, // 数据总数量
      dialogFormVisible: false, // 控制对话框的显示与隐藏
      form: {
        tmName: '',
        logoUrl: ''
      },
      imageUrl: '', // 上传图片要用的属性
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { validator: validateTmName, trigger: 'change' }
        ],
        logoUrl: [
          { required: true, message: '请上传品牌图片' }
        ]
      } // 校验规则
    }
  },
  mounted() {
    this.getTradeMarkList()
  },
  methods: {
    // 删除按钮被点击
    async removeTradeItemFn(id) {
      try {
        await this.$confirm('此操作将永久删除该文件')
        const { removeTradeMark } = this.$API.trademark
        await removeTradeMark(id)
        this.getTradeMarkList(this.tableData.length > 0 ? this.page.page : this.page.page - 1)
      } catch (error) {
        console.log('取消删除')
      }
    },
    handleAvatarSuccess(res, file) {
      // res时上传成功后返回的前端数据,file时上传成功后返回的服务端数据
      this.form.logoUrl = res.data
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 确定按钮被点击
    async configDialogFn() {
      try {
        await this.$refs.form.validate()
        const { addTradeMark, editTradeMark } = this.$API.trademark
        if (this.form.id) {
          const res = await editTradeMark(this.form)
          // console.log(res);
          if (res.code === 200) {
            this.$message.success(res.message)
          } else {
            this.$message.warning(res.message)
          }
        } else {
          const res = await addTradeMark(this.form)
          // console.log(res);
          if (res.code === 200) {
            this.$message.success(res.message)
          } else {
            this.$message.warning(res.message)
          }
        }
        this.getTradeMarkList(this.form.id ? this.page.page : 1)
        this.closeDialogFn()
      } catch (error) {
        console.log('请输入合法信息')
      }
    },
    // 取消按钮被点击
    closeDialogFn() {
      this.$refs.form.resetFields()
      this.dialogFormVisible = false
      this.form = {
        tmName: '',
        logoUrl: ''
      }
      this.imageUrl = ''
    },
    // 新增品牌按钮被点击
    showDialogFn(row = {}) {
      // console.log(row);
      if (row.id) {
        // 浅拷贝，如果直接等号赋值则把指针指向改变，只要数据已发生改变即使点击取消按钮也会把数据改掉
        this.form = { ...row }
        this.imageUrl = row.logoUrl
      }
      this.dialogFormVisible = true
    },
    // 每一页展示多少条数据
    handleSizeChange(limit) {
      this.page.limit = limit
      this.getTradeMarkList()
    },
    // 分页器页码发生改变
    handleCurrentChange(page) {
      this.page.page = page
      this.getTradeMarkList()
    },
    // 获取数据
    async getTradeMarkList() {
      // console.log(this.$API);
      const { getTradeMark } = this.$API.trademark
      const res = await getTradeMark(this.page)
      console.log(res)
      if (res.code === 200) {
        this.tableData = res.data.records
        this.total = res.data.total
      }
    }
  }
}
</script>

<style lang="scss">
.img{
  width: 300px;
  height: 150px;
}

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
